<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width: 100%;">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10,100]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <!-- <el-pagination layout="prev, pager, next" /> -->
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hResetForm">
        <addEmployees ref="addEmployee" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="roleshowDialog">
        <!-- 分配角色 -->
        <assignRole v-if="roleshowDialog" :id="curId" @success="hAssignRoleSuccess" @close="roleshowDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignRole from './assignRole.vue'
import { getEmployees, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
import addEmployees from './empDialog.vue'

// const hireType = {}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// console.log(hireType)

const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
console.log(hireType, 'hireType')
export default {
  components: {
    addEmployees,
    assignRole
  },
  data() {
    return {
      roleshowDialog: false,
      showDialog: false,
      page: 1,
      size: 5,
      list: [],
      total: 0,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRoleSuccess() {
      this.roleshowDialog = false
    },
    hAssignRole(id) {
      this.curId = id
      this.roleshowDialog = true
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出一个数据对象
      const one = list[0]
      // 判断one是否有值，如果没有直接终止程序
      if (!one) return
      //   list中没有数据
      // console.log(Object.keys(one),'Object.keys(one)');
      // 使用对象生成需要的header数据
      const header = Object.keys(one).map(enKey => {
        // console.log(enKey,'enKey')
        // console.log(map[enKey],'map[enKey]');
        return map[enKey]
      })
      console.log(header, 'header')

      const data = list.map(item => {
        const key = item.formOfEmployment
        // console.log(hireType[key], ' hireType[key]')
        // console.log(hireType, 'hireType')
        item['formOfEmployment'] = hireType[key] || '未知'
        // console.log(item,'item')
        // console.log(Object.values(item),'Object.values(item)')
        return Object.values(item)
      })

      return { header: header, data: data }
    },
    async handleDownload() {
      try {
        const res = await getEmployees()
        console.log('getEmployees', res)
        const { header, data } = this.formatData(res.data.rows)
        //  import('@/vendor/Export2Excel')  懒加载的方式导入一个模块（文件）返回值是一个promise实例
        import('@/vendor/Export2Excel').then(excel => {
          // excel 指的是模块对象，可以使用excel调用 Export2Excel文件中的函数或者使用Export2Excel文件中的变量

          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        // 保存数据
      } catch (err) {
        console.log('getEmployees', err)
      }
    },
    hDel(id) {
      this.$confirm('确认删除吗?').then(async() => {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) { this.page = 1 }
        }
        this.loadEmployees()
      }).catch((error) => {
        console.log(error)
      })
    },
    hResetForm() {
      this.$refs.addEmployee.resetForm()
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    formOfEmploymentFormat(data) {
      // return EmployeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        console.log(res, 'res')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
